/*
 * @Author: your name
 * @Date: 2020-08-07 14:08:25
 * @LastEditTime: 2021-01-20 15:17:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \myReposCode\Thread\th1.cpp
 */
#include <iostream>
#include <Windows.h> // for Sleep()
#include <thread>
#include <mutex>
#include <cstdlib>

#include <regex>

using namespace std;

// 可调用的对象1：函数
void func01(int& a)
{
    cout << "This is a new thread." << endl;
    Sleep(3000);
    cout << "a = " << a << endl;
}

// 可调用的对象2：仿函数
class A
{
public:
    void operator()(){
        cout << "this is a fangHanShu!!!" << endl;
    }

    int getSum(int &a, int &b)
    {
        // std::lock_guard<std::mutex> mylock(mymutex);
        std::unique_lock<std::mutex> mylock(mymutex);
        // mymutex.lock();
        cout << "a + b = " << a + b <<endl;
        a = 333;
        cout << "a = " << a << endl;
        return a + b;
        // mymutex.unlock();
    }

private:
    std::mutex mymutex;
};

int main()
{
    A a;
    // 可调用的对象3：lambda表达式
    auto lambda = [](){
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "-------exit--------" << endl;
        exit(0);
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
        cout << "this is a lambda..." << endl;
    }; 

    thread th1(lambda);
    th1.detach();
    cout << "...Main thread..." << endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    cout << "...Main thread..." << endl;
    // std::this_thread::sleep_for(std::chrono::seconds(3));
    bool b = th1.joinable();
    cout << b << endl;


    // int aa = 2;
    // int bb = 3;
    // thread th2(&A::getSum, &a, std::ref(aa), std::ref(bb));
    // th2.join();
    // cout << "aa = " << aa << endl;
    
    return 0;    
}